package com.zk.monitormanagement.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;


import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;


import com.zk.monitormanagement.constant.ManageConstants;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class QiniuUtils {

	private AsyncExecutor executor;
	private Context context;

	/**七牛地址前缀*/
	public static String QINIUHOST = "http://qiniucloud.zklj.com.cn/";

	private QiniuUtils(Context context) {
		this.context = context;
		executor = new AsyncExecutor();
	}

	public static QiniuUtils from(Context context) {
		return new QiniuUtils(context);
	}


	/**
	 * bitmap
	 * @param file
	 * @param callback
     */
	public void queue(final File file, final UploadListener callback) {
		new Handler(Looper.getMainLooper()).post(new Runnable() {
			@Override
			public void run() {
				//创建Request对象，并传入请求地址
				final Request request = new Request.Builder().url(ManageConstants.GET_QINIU_CODE).build();
				//创建OkHttpClient对象：目的是通过OkHttpClient初始化Call对象
				OkHttpClient client = new OkHttpClient();
				//构造Call对象--其实是AsyncCall对象
				Call call = client.newCall(request);
				//调用Call.enqueue方法进行异步请求
				call.enqueue(new Callback() {
					@Override
					public void onFailure(Call call, IOException e) {
						//网络请求失败
						callback.onError(1);
						Log.d("sss", "onFailure: " + e.getMessage());
					}

					@Override
					public void onResponse(Call call, Response response) throws IOException {
//						Log.d("sss", "上传成功: " + response.body().string());
						//网络请求成功
//						JSONObject jsonObject = JsonUtils.parseFromJson(response.body().string());

						try {
							JSONObject jsonObject=new JSONObject(response.body().string());
							if (JsonUtils.getJsonString(jsonObject, "status") .equals("1")) {
								UploadWorker worker = new UploadWorker(file, JsonUtils.getJsonString(jsonObject, "token"),
										callback);
								executor.execute(worker);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}




					}
				});
			}
		});

	}

	/**
	 * mp3
	 * @param file
	 * @param callback
     */
	public void queueWave(final File file, final UploadListener callback) {
		new Handler(Looper.getMainLooper()).post(new Runnable() {
			@Override
			public void run() {

				//创建Request对象，并传入请求地址
				Request request = new Request.Builder().url(ManageConstants.GET_QINIU_CODE).build();
				//创建OkHttpClient对象：目的是通过OkHttpClient初始化Call对象
				OkHttpClient client = new OkHttpClient();
				//构造Call对象--其实是AsyncCall对象
				Call call = client.newCall(request);
				//调用Call.enqueue方法进行异步请求
				call.enqueue(new Callback() {
					@Override
					public void onFailure(Call call, IOException e) {
						callback.onError(1);
					}

					@Override
					public void onResponse(Call call, Response response) throws IOException {
						JSONObject jsonObject = JsonUtils.parseFromJson(response.body().string());
						if (JsonUtils.getJsonInt(jsonObject, "status") == 1) {
							UploadWorkerWAV worker = new UploadWorkerWAV(file, JsonUtils.getJsonString(jsonObject, "token"),
									callback);
							executor.execute(worker);
						}
					}
				});
			}
		});

	}

	private class UploadWorker extends AsyncExecutor.Worker<String> {

		private File file;
		private UploadListener callback;
		private String token;
		private UploadManager uploadManager = new UploadManager();

		public UploadWorker(File file, String token, UploadListener l) {
			this.file = file;
			this.token = token;
			this.callback = l;

		}

		@Override
		protected String doInBackground() {

			String newpath = SDCardUtil.getRandomFileName() + ".png";

			uploadManager.put(file, newpath, token, new UpCompletionHandler() {
				@Override
				public void complete(String key, com.qiniu.android.http.ResponseInfo info, JSONObject response) {
					Log.e("sss",response.toString());
//					try {
						if (info.statusCode==200) {
							// 上传图片返回key值
							try {
								callback.onSuccess(file,QINIUHOST+response.getString("key"));
							} catch (JSONException e) {
								Log.e("sss","错误大妈"+e.getMessage());
								e.printStackTrace();
								callback.onError(1);
							}
//							callback.onSuccess(file, QINIUHOST+JsonUtils.getJsonString(response, "key"));
						} else {
							callback.onError(info.statusCode);
						}
//					} catch (Exception e) {
////						Log.e("sss","错误大妈"+e.getMessage());
//						e.printStackTrace();
//						callback.onError(1);
//					}
				}
			}, null);
			return null;
		}
	}


	private class UploadWorkerWAV extends AsyncExecutor.Worker<String> {

		private File file;
		private UploadListener callback;
		private String token;
		private UploadManager uploadManager = new UploadManager();

		public UploadWorkerWAV(File file, String token, UploadListener l) {
			this.file = file;
			this.token = token;
			this.callback = l;

		}

		@Override
		protected String doInBackground() {

			String newpath = SDCardUtil.getRandomFileName() + ".mp3";


			uploadManager.put(file, newpath, token, new UpCompletionHandler() {
				@Override
				public void complete(String key, com.qiniu.android.http.ResponseInfo info, JSONObject response) {
					try {
						if (info.statusCode == 200) {
							// 上传图片返回key值
							callback.onSuccess(file, QINIUHOST+JsonUtils.getJsonString(response, "key"));
						} else {
							callback.onError(info.statusCode);
						}
					} catch (Exception e) {
						e.printStackTrace();
						callback.onError(1);
					}
				}
			}, null);
			return null;
		}
	}

	public interface UploadListener {
		void onSuccess(File compressedFile, String key);

		void onError(int code); // TODO 定义自己的错误码
	}
}
